<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/17
 * Time: 14:54
 */
namespace app\home\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\request;

/**
 *
 * 期货出入金
 */
class Futures extends Base
{
    
    public function  publi()
    {
        //此账号是否开户
        $ste = Db::name('users')->where('id='.Session::get('uid'))->field('assetaccount,balance')->find();
        if ($ste['assetaccount'] !== '' and $ste['assetaccount'] != '00000') {
            $qjgjz = Db::name('futures_api')->where('state=1')->find();
         
            header("Content-type: text/html; charset=utf-8");
            $requestid = 6;                                   //用户结果与请求统一的值
            // $sa='qjgj';                                     //期货管理员账号
            // $sapass='123';                                  //期货管理员密码
            $account = $ste['assetaccount'];                               //用户账号
            $url = $qjgjz['api'] . "queryaccount?requestid=" . $requestid . "&sa=" . $qjgjz['sa'] . "&sapass=" . $qjgjz['sapass'] . "&account=" . $account;
            //echo $url;
            $curl = curl_init(); // 启动一个CURL会话
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
            $tmpInfo = curl_exec($curl);     //返回api的json对象
            //关闭URL请求
            curl_close($curl);
            $arr = simplexml_load_string($tmpInfo);
            $xmljson = json_encode($arr);//将对象转换个JSON
            $xmlarray = json_decode($xmljson, true);//将json转换成数组
            $ar = $xmlarray['Result'];
            //var_dump($ar);die;
            $data = array();
            if(!isset($ar['Summary'])){
                $ar['Summary']=1;
               return $ar['Summary'];
            }else{
            $data = $ar['Summary'];

            //劣后资金
            $data['bad'] = $data['Balance'] - $data['Credit'];
            //var_dump($data['bad']);

            return $data;
        }
        } else {
            return "<script>alert('请先申请账号');window.location.href='" . url('/home/Openanaccount/index') . "'</script>";
            //$this->success('请先申请账号','userpersonal/personalCenter');
        }
    }
    public function withdraw()
    {
    	$ste = Db::name('users')->where('id=' . Session::get('uid'))->field('assetaccount,balance,fwq')->find();
    	if($ste['assetaccount'] == '' and $ste['assetaccount'] = '00000'){
               return "<script>alert('请先申请账号');window.location.href='" . url('/home/Openanaccount/index') . "'</script>";
            }
    	$qjgjz = Db::name('futures_api')->where('id',$ste['fwq'])->find();
    	if($qjgjz['title']=='jt'){
    	}else{
        $ste = Db::name('users')->where('id=' . Session::get('uid'))->field('assetaccount,balance')->find();
        if ($ste['assetaccount'] == '' and $ste['assetaccount'] = '00000') {
            return "<script>alert('请先申请账号');window.location.href='" . url('/home/Openanaccount/index') . "'</script>";
        }
    	//期金管家
        $data = $this->publi();
        if($data==1){
            return "<script>alert('期货账号有问题，请联系客服！');window.location.href='".url('home/Deposit/deposit')."'</script>";
        }
        $this->assign('ste', $ste);
        $this->assign('data', $data);
        //是否post表单提交
        if (Request::instance()->isPost()){
            //var_dump($_POST);die;
            $data = $this->publi();
            $time = Db::name('config')->where('key', 'jstime')->find()['value'];
            $s = explode('-', $time);
           // var_dump($s);die;
            if (date('H:i') >= $s[0] && date('H:i') <= $s[1]) {
                $this->error("$s[0]~$s[1]时为结算时间，不允许出入金", 'Futures/withdraw');
            }
            // $op = Db::name('user_allocation')->where(['uid'=>Session::get('uid'),'status'=>1])->find();
            // if($op){
            // 	$this->error('出金失败请先取消配资','userfutures/index');
            // }
            // $data['bad'];die;
            $payCj =trim($_POST['payCj']);  //期货出入金
            if (preg_match("/[\',:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $payCj)) {
                return "<script>alert('请输入正确的金额');window.location.href='" . url('/home/Futures/withdraw') . "'</script>";
            }
            if ($payCj/100 <= 0) {
                return "<script>alert('出入金额必须大于0');window.location.href='" . url('home/Futures/withdraw') . "'</script>";
            }
            //是否有保证金，有保证金就不能出金
            if ($data['Margin'] == 0) {
            if($_POST['codes'] != Session::get('codes')){
		    	$this->error('正在处理您的请求请稍后~','Futures/withdraw');
		      }
		    Session::set('codes',mt_rand(1000,9999));
                //出金
                //var_dump($data['Credit']);
                $qjgjz = Db::name('futures_api')->where('state=1')->find();
                if ($data['bad'] >= $payCj) {
                    $requestid = 6;                    //用户结果与请求统一的值
                    $account = $ste['assetaccount'];   //用户户账号
                    $amount = '-' . $payCj;              //出金金额
                    $credit = 0; //$data['Credit'];    //优先资金
                    $remark = iconv("UTF-8", "GBK", '期货转账户');
                    // $remark=$remark;
                    $url = $qjgjz['api']."deposit?requestid=".$requestid."&sa=".$qjgjz['sa']."&sapass=".$qjgjz['sapass']."&account=".$account."&amount=".$amount."&credit=".$credit."&remark=".$remark;
                    $curl = curl_init(); // 启动一个CURL会话
                    curl_setopt($curl, CURLOPT_URL, $url);
                    curl_setopt($curl, CURLOPT_HEADER, 0);
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
                    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
                    $tmpInfo = curl_exec($curl);     //返回api的json对象
                    //关闭URL请求
                    curl_close($curl);
                    $arr = simplexml_load_string($tmpInfo);
                    $xmljson = json_encode($arr);//将对象转换个JSON
                    $xmlarray = json_decode($xmljson, true);//将json转换成数组
                    $ar = $xmlarray['Result'];
                    //var_dump($ar);die;
                    //出入金记录
                    //var_dump($ar);exit;
                    $list = array();
                    $list['uid'] = Session::get('uid');
                    $list['futuresID'] = $account;
                    $list['eae'] = 0;
                    $list['amount'] = $payCj;
                    $list['del'] = $ar['Error']['Code'];
                    $list['remakes'] = '期货转用户';
                    //$res = $this->find_log_balance();
                    //是否出金成功 0是入金成功
                    if ($ar['Error']['Code']==0){
                        //出金成功增加余额
                        $price = $ste['balance'] + $payCj;
                        //资金日志余额
                        $zij = Db::name('cashlog')->where('uid=' . Session::GET('uid'))->order('id desc')->limit(0, 1)->find();
                        $prices = $zij['balance'] + $payCj;
                        //资金日志
                        $dat = array();
                        $dat['uid'] = Session::get('uid');
                        $dat['type'] = 6;
                        $dat['price'] = $payCj;
                        $dat['balance'] = $prices;
                        Db::name('user_futures')->insertGetId($list);
                        Db::name('cashlog')->insertGetId($dat);
                        $arr = Db::table('qfll_users')->where('id', Session::get('uid'))->update(['balance' => $price]);
                        //return  "<script>alert('出金成功');window.location.href='".url('home/Userfutures/index')."'</script>";
                        $this->success('出金成功', 'Futures/withdraw');
                    }else {
                        //return  "<script>alert('出金失败请重试');window.location.href='".url('home/Userfutures/index')."'</script>";
                        $this->error('出金失败请重试', 'Futures/withdraw');
                    }
                } else {
                    //return  "<script>alert('出金金额不足');window.location.href='".url('home/Userfutures/index')."'</script>";
                    $this->error('出金金额不足', 'Futures/withdraw');
                }
            } else {
                //return  "<script>alert('请全部平仓后再出金');window.location.href='".url('home/Userfutures/index')."'</script>";
                $this->error('请全部平仓后再出金', 'Futures/withdraw');
            }

        }
      }
        return $this->fetch('Futures/withdraw');
    }

    //入金
    public function  golden()
    {
    	$ste = Db::name('users')->where('id=' . Session::get('uid'))->field('assetaccount,balance,fwq')->find();
    	if ($ste['assetaccount'] == '' and $ste['assetaccount'] = '00000'){
                  return "<script>alert('请先申请账号');window.location.href='" . url('/home/Openanaccount/index') . "'</script>";
             }    
    	$qjgjz = Db::name('futures_api')->where('id',$ste['fwq'])->find();      
    	if($qjgjz['title']=='jt'){
           //吉投
             $data=$this->jitou();
             if($data==1){
               return "<script>alert('期货账号有问题，请联系客服！');window.location.href='".url('home/Deposit/deposit')."'</script>";
             }
		        $this->assign('ste', $ste);
		        $this->assign('data', $data);
        //是否post表单提交
        if (Request::instance()->isPost()){
        	
        	
        	     //账户是否异常
		         $str=Db::name('user_withdrawcash')->where('uid',Session::GET('uid'))->where('state','in','1,2')->sum('amount');
		         $strr=Db::name('user_withdrawcash')->where('uid',Session::GET('uid'))->where('state','in','1,2')->sum('poundage');
		         //资金日志
		         $zij=Db::name('cashlog')->where('uid='.Session::GET('uid'))->order('id desc')->limit(0,1)->find();
		         //用户余额加提现未到账
		         $ste = Db::name('users')->where('id=' . Session::get('uid'))->field('assetaccount,balance')->find();
//		         var_dump($str);
//		         var_dump($strr);
		         $zamount=$ste['balance']+$str+$strr;
		         //数据是否异常
//		         var_dump($zij['balance']);
//		         var_dump($zamount);die;
		         if($zij['balance']!=$zamount){
		            return  "<script>alert('用户余额和资金日志异常,请联系客服！');window.location.href='".url('home/Futures/golden')."'</script>";
		          }
		          
		          
        	    $data=$this->jitou();
	        	$time = Db::name('config')->where('key', 'jstime')->find()['value'];
	            $s = explode('-', $time);
	            if (date('H:i') >= $s[0] && date('H:i') <= $s[1]) {
	                $this->error("$s[0]~$s[1]时为结算时间，不允许出入金", 'Futures/withdraw');
	            }
        	    $payRj =round(trim($_POST['payRj']),2)*100;  //期货出入金
        	    //配资金额
        	    $payRz =round(trim($_POST['payPz']),2)*100;
        	    if($payRz>500000000){
        	    	 return "<script>alert('配资金额最大不能超过500万，请联系客服处理！');window.location.href='" . url('/home/Futures/golden') . "'</script>";
        	    }
        	    
	          /*  if (preg_match("/[\',:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $payRj)) {
	                return "<script>alert('请输入正确的金额');window.location.href='" . url('/home/Futures/withdraw') . "'</script>";
	           }*/
	            if($payRj/100 <= 0) {
	                return "<script>alert('出入金额必须大于0');window.location.href='" . url('home/Futures/golden') . "'</script>";
	              }
        	    if($_POST['codes'] != Session::get('codes')){
		    	   $this->error('正在处理您的请求请稍后~','Futures/withdraw');
		         }
		         
		        Session::set('codes',mt_rand(1000,9999));
		        if($ste['balance']>=$payRj/100){
		       	//配资要小于等于10倍
		       	//(劣后资金+入金金额)*10>=配资金额

		       	if(($data['bad']*100*10+$payRj*10)<$payRz){
		       		 return  "<script>alert('配资资金过大请重新输入');window.location.href='".url('home/Futures/golden')."'</script>";
		       	}
		       	//账户本来的优先资金
		       	$bpay=($data['Available']-$data['bad'])*100;
		       	//新的配资-账户本来的优先资金=需要的优先资金
		       	 $PriorityAmount=$payRz-$bpay;
        	    //金额是以分为单位
           	    $req['Action']='ReqTransfer';
                $req['ChdAccountID']=$ste['assetaccount'];
                $req['PriorityAmount']=0;
                $req['BadAmount']=$payRj;
                //var_dump($payCj);
                $req['UserID']=$qjgjz['sa'];
                ksort($req);
                $url='';
                foreach ($req as $k=>$v){
                    $url=$url.$k.'='.$v.'&';
                }
                $req=rtrim($url,'&');
                //var_dump($req);
                $sign=md5($req.'&UserKey='.$qjgjz['sapass']);
                $req=$req.'&Sign='.$sign;
                //var_dump($req);
                $url=$qjgjz['api'].'?'.$req;
                 // var_dump($url);die;
                $res=https_request($url);
               // var_dump($res);
                $ar=json_decode($res,true);
                if($ar['ErrorID']==0 ){
                	//出入金表
                	$list = array();
                    $list['uid'] = Session::get('uid');
                    $list['futuresID'] = $ste['assetaccount'];
                    $list['eae'] = 1;
                    $list['amount'] = '-'.$payRj/100;
                    $list['del'] = 1;
                    $list['remakes'] = '账户转期货';
                    Db::name('user_futures')->insertGetId($list);
                      //出金成功增加余额
                    $price = $ste['balance'] -$payRj/100;
                    $arr = Db::table('qfll_users')->where('id', Session::get('uid'))->update(['balance' => $price]); 
                    //资金日志余额
                    $zij = Db::name('cashlog')->where('uid=' . Session::GET('uid'))->order('id desc')->limit(0, 1)->find();
                    $prices = $zij['balance'] -$payRj/100;
                    //资金日志
                    $dat = array();
                    $dat['uid'] = Session::get('uid');
                    $dat['type'] = 5;
                    $dat['price'] = '-'.$payRj/100;
                    $dat['balance'] = $prices;
                	Db::name('cashlog')->insertGetId($dat);
                	
                }else{
                	$this->error($ar['ErrorMsg'], 'Futures/golden');
                }
                
                if($PriorityAmount==0){
                	$this->success('入金成功', 'Futures/golden');
                }
								if(Request::instance()->post('sf')==1){
                	$this->success('入金成功', 'Futures/golden');die;
                }
                
                $req=[];
                $req['Action']='ReqTransfer';
                $req['ChdAccountID']=$ste['assetaccount'];
                $req['PriorityAmount']=$PriorityAmount;
                $req['BadAmount']=0;
                //var_dump($payCj);
                $req['UserID']=$qjgjz['sa'];
                ksort($req);
                $url='';
                foreach ($req as $k=>$v){
                    $url=$url.$k.'='.$v.'&';
                }
                $req=rtrim($url,'&');
                //var_dump($req);
                $sign=md5($req.'&UserKey='.$qjgjz['sapass']);
                $req=$req.'&Sign='.$sign;
                //var_dump($req);
                $url=$qjgjz['api'].'?'.$req;
                 // var_dump($url);die;
                $res=https_request($url);
               // var_dump($res);
                $ar1=json_decode($res,true);
                if($ar1['ErrorID']==0 && $ar['ErrorID']==0){
                	//配资表
                	$pz=array();
                	$pz['uid']=Session::get('uid');
                	$pz['futuresID']=$ste['assetaccount'];
                	$pz['priorityfunds']=$PriorityAmount/100;
                	$pz['action']=($payRz/100).'-'.($bpay/100);
                	if($PriorityAmount<0){
                			$pz['eae']=0;
                	}else{
                		$pz['eae']=1;
                	}
                	$pz['state']=0;
                	$pz['addtime']=date('Y-m-d H:i:s');
                	Db::name('allocationpriority')->insertGetId($pz);
                	//出入金表
                
                	 $this->success('入金成功', 'Futures/golden');
                }else{
                	$this->error($ar1['ErrorMsg'], 'Futures/golden');
                }
                }else{
                	  $this->error('入金金额不足', 'Futures/golden');
                     }
               
    		    }
    
    	}else{
	    	   $ste = Db::name('users')->where('id=' . Session::get('uid'))->field('assetaccount,balance')->find();
	        if ($ste['assetaccount'] == '' and $ste['assetaccount'] = '00000') {
	            return "<script>alert('请先申请账号');window.location.href='" . url('/home/Openanaccount/index') . "'</script>";
	        }	
	        $data = $this->publi();
	        if($data==1){
	            return "<script>alert('期货账户有问题，请联系客户！');window.location.href='".url('home/Deposit/deposit')."'</script>";
	        }
	        $this->assign('ste', $ste);
	        $this->assign('data', $data);
	        if (Request::instance()->isPost()){
	
	            //账户是否异常
	            $str=Db::name('user_withdrawcash')->where('uid='.Session::GET('uid').' and state=1 or state=2')->sum('amount');
	            $strr=Db::name('user_withdrawcash')->where('uid='.Session::GET('uid').' and state=1 or state=2')->sum('poundage');
	            //资金日志
	            $zij=Db::name('cashlog')->where('uid='.Session::GET('uid'))->order('id desc')->limit(0,1)->find();
	            //用户余额加提现未到账
	            $ste = Db::name('users')->where('id=' . Session::get('uid'))->field('assetaccount,balance')->find();
	            $zamount=$ste['balance']+$str+$strr;
	            //数据是否异常
	            if($zij['balance']!=$zamount){
	                return  "<script>alert('用户余额和资金日志异常,请联系客服！');window.location.href='".url('home/Futures/golden')."'</script>";
	            }
	            $data = $this->publi();
	            $time = Db::name('config')->where('key', 'jstime')->find()['value'];
	            $s = explode('-', $time);
	            //var_dump($s);die;
	            if (date('H:i') >= $s[0] && date('H:i') <= $s[1]) {
	                $this->error("$s[0]~$s[1]时为结算时间，不允许出入金", 'Futures/golden');
	            }
	                $payRj =trim($_POST['payRj']);  //期货入金
	                 //配资金额
        	        $payRz =round(trim($_POST['payPz']),2);
	                if (preg_match("/[\',:-;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $payRj)) {
	                    return "<script>alert('请输入正确的金额1');window.location.href='" . url('/home/Futures/golden') . "'</script>";
	                }
	                if ($payRj <0) {
		                return "<script>alert('出入金额必须大于0');window.location.href='" . url('home/Futures/golden') . "'</script>";
		            }
		            //配资
		            if ($payRz < 0) {
		                return "<script>alert('出入配资不能小于0');window.location.href='" . url('home/Futures/golden') . "'</script>";
		            }
		            if($payRz>5000000){
        	    	 return "<script>alert('配资金额最大不能超过500万，请联系客服处理！');window.location.href='" . url('/home/Futures/golden') . "'</script>";
        	        }
        	    
			        if($_POST['codes'] != Session::get('codes')){
					    $this->error('正在处理您的请求请稍后~','Futures/golden');
					}
					 //配资要小于等于10倍
			       	//(劣后资金+入金金额)*10>=配资金额
			       	if(round(($data['bad']*10+$payRj*10),2)<round($payRz,2)){
			       		 return  "<script>alert('配资资金过大请重新输入');window.location.href='".url('home/Futures/golden')."'</script>";
			       	}
			       	//新的配资-账户本来的优先资金=需要的优先资金
			       	$PriorityAmount=$payRz-$data['Credit'];
			       
					if(Request::instance()->post('sf')==1){
						$PriorityAmount=0;
					}
				    //echo  $payRj.'------配资：'.$PriorityAmount;die;
					Session::set('codes',mt_rand(1000,9999));
	                //入金
	                $qjgjz = Db::name('futures_api')->where('state=1')->find();
	                if ($ste['balance'] >= $payRj AND $payRj >= 0) {
	                    $requestid = 6;                    //用户结果与请求统一的值
	                    $account = $ste['assetaccount'];   //用户户账号
	                    $amount =$payRj+$PriorityAmount;                  //入金金额
	                    $credit =$PriorityAmount;                //优先资金
	                    $remark = iconv("UTF-8", "GBK", '账户转期货');
	                    $url = $qjgjz['api']."deposit?requestid=".$requestid."&sa=".$qjgjz['sa']."&sapass=".$qjgjz['sapass']."&account=".$account."&amount=".$amount."&credit=".$credit."&remark=".$remark;
	                    $curl = curl_init(); // 启动一个CURL会话
	                    curl_setopt($curl, CURLOPT_URL, $url);
	                    curl_setopt($curl, CURLOPT_HEADER, 0);
	                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	                    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
	                    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
	                    $tmpInfo = curl_exec($curl);     //返回api的json对象
	                    //关闭URL请求
	                    curl_close($curl);
	                    $arr = simplexml_load_string($tmpInfo);
	                    $xmljson = json_encode($arr);//将对象转换个JSON
	                    $xmlarray = json_decode($xmljson, true);//将json转换成数组
	                    $ar = $xmlarray['Result'];
	                    //dump($ar);die;
	                    //出入金记录
	                    //var_dump($ar);exit;
	                    $list = array();
	                    $list['uid'] = Session::get('uid');
	                    $list['futuresID'] = $account;
	                    $list['eae'] = 1;
	                    $list['amount'] = '-' . $payRj;
	                    $list['del'] = $ar['Error']['Code'];
	                    $list['remakes'] = '账户转期货';
	                    
	                    //配资表
	                	$pz=array();
	                	$pz['uid']=Session::get('uid');
	                	$pz['futuresID']=$ste['assetaccount'];
	                	$pz['priorityfunds']=$PriorityAmount;
	                	$pz['action']=$payRz.'-'.$data['Credit'];
	                	if($PriorityAmount<0){
	                			$pz['eae']=0;
	                	}else{
	                		$pz['eae']=1;
	                	}
	                	$pz['state']=0;
	                	$pz['addtime']=date('Y-m-d H:i:s');
	                	Db::name('allocationpriority')->insertGetId($pz);
	                    
	                    //是否入金成功 0是入金成功
	                    if ($ar['Error']['Code'] == 0) {
	                    	
	                        //入金成功扣除余额
	                        $price = $ste['balance'] - $payRj;
	                        // 资金日志余额
	                        $zij = Db::name('cashlog')->where('uid=' . Session::GET('uid'))->order('id desc')->limit(0, 1)->find();
	                        $prices = $zij['balance'] - $payRj;
	                        //资金日志
	                        $dat = array();
	                        $dat['uid'] = Session::get('uid');
	                        $dat['type'] = 5;
	                        $dat['price'] = '-' . $payRj;
	                        $dat['balance'] = $prices;
	                        Db::name('user_futures')->insertGetId($list);
	                        Db::name('cashlog')->insertGetId($dat);
	                        $arr = Db::table('qfll_users')->where('id', Session::get('uid'))->update(['balance' => $price]);
	
	                        //return  "<script>alert('入金成功');window.location.href='".url('home/Userfutures/index')."'</script>";
	                        $this->error('入金成功', 'Futures/golden');
	                    } else {
	                        //return  "<script>alert('入金失败请重试');window.location.href='".url('home/Userfutures/index')."'</script>";
	                        $this->error($ar['Error']['Message'], 'Futures/golden');
	                    }
	
	                }else{
	                    return  "<script>alert('请输入正确的金额');window.location.href='".url('home/Futures/golden')."'</script>";
	                }
	        }
        }
        return $this->fetch('Futures/golden');
    }
}